<template>
  <div style="flex: 90%; margin-top: 20px; margin-left: 20px">
    
    <el-form :inline="true" :model="data" class="demo-form-inline">
      <el-form-item label="股票代码">
        <el-input
          v-model="data.code"
          style="width: 240px"
          placeholder="input stock code"
          @update:model-value="onInputChange"
      /></el-form-item>
      <el-form-item>
          <el-button type="primary" @click="clickAddFupanData()">添加复盘笔记</el-button>
        </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      ref="tableRef"
      row-key="code"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="code" label="代码" width="180" />
      <el-table-column prop="currentPrice" label="价格" width="180"/>
      <el-table-column prop="focus" label="操作" width="300" > 
        <template #default="scope">
          <el-button @click="handleBuySure(scope.$index, scope.row)"  
          type="primary" >
            签字确认
          </el-button>
        </template>  
      </el-table-column>
    </el-table>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="选日期">
          <el-date-picker
                  v-model="data.dateTime"
                  type="date"
                  placeholder="Pick a day"
                  size="large"
                  @change="handleDateChange"
              />
        </el-form-item>
    </el-form>

    <el-table
      ref="tableRef"
      row-key="code"
      :data="tableDataAll"
      style="width: 100%"
    >
        <el-table-column style="color: #990000;" prop="bigType" label="类型" :width="120" >
            <template #default="scope">
                <el-text style="color: #333333;font-weight: bold;font-size: 13px;">{{scope.row.bigType}}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="reviewName" label="名称" width="200" />
        <el-table-column prop="trend" label="走势" width="150"/>
        <el-table-column prop="isOk" label="是否通过"  width="150">
              <template #default="scope">
                <div class="button-container">
                  <el-button type="warning" circle size="small" v-show="shouldShowButton(scope.row, 0)" style="margin-left:12px">待</el-button>
                  <el-button type="danger" :icon="CloseBold" circle size="small" v-show="shouldShowButton(scope.row, 2)"/>               
                  <el-button type="success" :icon="Check" circle size="small" v-show="shouldShowButton(scope.row, 1)"/>
                </div>
              </template>
          </el-table-column>
        <el-table-column prop="url" label="复盘地址" width="100" >
          <template #default="scope">
            <a :href="scope.row.reviewUrl" target="_blank">复盘地址</a>
          </template>
        </el-table-column>
    </el-table>

  </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { TableColumnCtx, TableInstance } from "element-plus";
import { reactive } from "vue";
import axios from "axios";
import { countdownEmits, ElMessage, ElMessageBox} from "element-plus";
import ClipboardJS from 'clipboard';
import { useStore } from 'vuex';
import type { Action } from 'element-plus'
import {Check,Delete,Edit,Message,Search, Star, CloseBold,Close,QuestionFilled
} from '@element-plus/icons-vue';

const data = reactive({
  code: "",
  dateTime: "",
});

const onSearh = (str: string, type: number) => {
  console.log("submit!");
  const encodedName = encodeURIComponent(str);
  const api = "api/plat/stockOrder/getStockListByName?name=" + encodedName;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onSearhAll = () => {
  console.log("submit!");
  const api = "api/plat/stockDailyReview/findPageList/1/100?recordDate=" + data.dateTime;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableDataAll.value = response.data.data.list;
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onSubmit_UpdateOrder = (pid: number,pstatus:number) => {
  axios.put("api/plat/stockOrder/update", {
    id:pid,
    status:pstatus,
  }).then((response) => {
    console.log(response);
    if (response.data.status == 200) {
        ElMessage({
          message: "签字完成",
          type: "success",
        });
      } else {
        ElMessage({
          message: "签字失败",
          type: "success",
        });
      }
  })
}

interface StockOrder {
  id: number;
  name: string;
  code: string;
  focus: number;
  status: number;
}

interface StockDailyReview {
  id: number; // ID
  recordDate: string; // 日期
  bigType: string; // 大类型
  reviewName: string; // 任务名
  importLevel: number; // 重要性等级
  isOk: number; // 是否完成
  reviewType: number; // 任务类型
  otherType: number; // 其它分类
  reviewUrl: string; // 链接地址
  indicatorOkId: number; // 任务细则
  intA: number; // int_a
  intB: number; // int_b
  intC: number; // int_c
  floatA: number; // float_a
  floatB: number; // float_b
  floatC: number; // float_c
  strA: string; // str_a
  strB: string; // str_b
  strC: string; // str_c
  createTime: Date; // 创建时间
  updateTime: Date; // 更新时间
}

const onInputChange = (newValue, oldValue) => {
  onSearhAll();
  // console.log("Input changed:", newValue);
  // const containsChinese = /[\u4e00-\u9fa5]/.test(newValue);
  // if (containsChinese) {
  //   onSearh(newValue, 2);
  // } else if (newValue.length == 6) {
  //   onSearh(newValue, 1);
  // }
};


const clickAddFupanData = () => {
      // 显示确认框
      ElMessageBox.confirm(
        '是否确认添加复盘笔记？', '添加复盘笔记',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning' // 弹窗类型，可以是 'success', 'info', 'warning', 'error'
        }).then(() => {
            clickLoadFuPan()
        }).catch(() => {
        
        });
      };

const clickLoadFuPan = () => {
      console.log("submit!");
      const api = "api/plat/stockDailyReview/addFuPanData?dayTime=" + data.dateTime;
      console.log(api) 
      axios
        .get(api)
        .then((response) => {
          onSearhAll()
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    };

const handleDateChange = (val) => {
        console.log('选择了新的日期/时间:', val);
        const date = new Date(val)
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1
        const day = ('0' + date.getDate()).slice(-2);
        const dayTime = `${year}-${month}-${day}`;
        console.log('选择了新的日期/时间:', dayTime);

        const date1 = new Date(getToday());
        const date2 = new Date(dayTime);

        if (date1 < date2) {
          ElMessage({
            message: "日期不能晚于今天",
            type: "error",
          });
          return;
        }

        data.dateTime = dayTime;
        onSearhAll();
    };


const loading = ref(false);
const tableRef = ref<TableInstance>();

const tableData = ref([]);
const tableDataAll = ref([]);

const store = useStore();


var code = ''
onMounted(() => {
      data.dateTime = getToday();
      onSearhAll();
      const clipboard = new ClipboardJS('.btn-copy', {
        text: () => code
      });

      clipboard.on('success', (e) => {
        console.log('Text copied to clipboard');
        e.clearSelection();
      });

      clipboard.on('error', (e) => {
        console.error('Failed to copy text: ', e);
      });
    });

    const handleBuySure = (index: number, row: StockOrder) => {
          ElMessageBox.alert('请遵守交易记录，切勿随心操作，挣钱不易', '签字确认', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: '确定',
        center:true,
        callback: (action: Action) => {
          onSubmit_UpdateOrder(row.id, 10)
        },
      })
    };

    const getToday = () =>  {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
      const day = String(today.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    }

    const shouldShowButton = (row: StockDailyReview, value) => {
      if (row.isOk == value) {
        return true;
      }
    }
</script>
  
